﻿using FastMvc.Auth;
using FastMvc.Exceptions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace FastMvc.MiddleWare
{
    /// <summary>
    /// 登录检查中间件
    /// 处于接口调用之前，进行接口鉴权
    /// </summary>
    public class AuthHandlerMiddleware
    {
        private readonly RequestDelegate next;
        public AuthHandlerMiddleware(RequestDelegate next)
        {
            this.next = next;
        }
        private const string AUTH_HEAD = "Authorization";

        static bool NeedLogin = false; // 测试用，是否验证登录的开关

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                // - 登录信息
                if (NeedLogin &&
                    context.Request.Path.Value.StartsWith("/api")    // 仅检查api接口
                    && !context.Request.Path.Value.StartsWith("/api/login"))   // 不检查登录相关接口
                {
                    if (context.Request.Headers.ContainsKey(AUTH_HEAD)
                        && !string.IsNullOrEmpty(context.Request.Headers[AUTH_HEAD]))
                    {
                        var token = context.Request.Headers[AUTH_HEAD];
                        var userAuthInfo = await CheckLoginToken(token);
                        if (userAuthInfo == null)
                        {
                            throw new UnAuthException("登录信息错误！", true);
                        }
                        context.Items["UserAuth"] = userAuthInfo;
                    }
                    else
                    {
                        throw new UnAuthException("登录信息错误！", true);
                    }
                }

                // 最终检查通过
                await next.Invoke(context);
            }
            catch (System.Exception ex)
            {
                throw;
            }
        }

        private async Task<UserAuthInfo> CheckLoginToken(string token)
        {
            return new UserAuthInfo()
            {
                sUserId = "7bfd5f91-1199-45e7-98a2-16dd3ab00534",
                sUserName = "系统管理员",
                Claims = new Dictionary<string, string>(),
            };

            var url = System.Configuration.ConfigurationManager.AppSettings["LoginUrl"] + "/api/login";

            var PostData = new { Token = token };

            var re = await HttpHelper.PostAsync<UserAuthInfo>(url, PostData);
            if (re.success)
            {
                return re.data;
            }
            return null;
        }
    }

    public static class AuthHandlerMiddlewareExt
    {
        public static IApplicationBuilder UseAuthHandler(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<AuthHandlerMiddleware>();
        }
    }
}
